package util;

import domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import mapper.UserMapper;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDao {
    private static SqlSessionFactory factory;
    static {
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("sqlMapConfig.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //JDK动态代理实现
    @Test
    public void context(){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = (UserMapper) Proxy.newProxyInstance(ProxyDao.class.getClassLoader(), new Class<?>[]{UserMapper.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String sqlId = proxy.getClass().getInterfaces()[0].getName()+"."+method.getName();
                return sqlSession.selectOne(sqlId,args[0]);
            }
        });
        User one = userMapper.findOne(41);
        System.out.println(one);
        sqlSession.close();
    }

    //myBatis Dao代理实现
    @Test
    public void testMapper(){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User one = mapper.findOne(41);
        System.out.println(one);
        sqlSession.close();
    }


}
